<template>
  <div class="live-view" v-loading="loading">
    <div class="live-left">
      <video 
        name="videoElement" 
        id="videoElement" 
        width="1024" height="576"
        class="live-video" controls  muted>
                Your browser is too old which doesn't support HTML5 video.
      </video>
    </div>

    
    <div class="live-right">

        <div class="live-right-header">

          <div class="live-right-header-info">

              <div class="live-info">
                <div class="live-info-item"><i class="el-icon-monitor"></i> {{liveInfo.liveName}}</div>
                <div class="live-info-item"><i class="el-icon-user"></i> {{liveInfo.teaName}}</div>
                <div class="live-info-item"><i class="el-icon-reading"></i> {{liveInfo.courseName}}</div>
                
                
              </div>
              <div class="close-live">

                    <el-tooltip effect="dark" content="退出" placement="left">
                        <router-link to="/course" class="close-link">
                            <i class="el-icon-close"></i>
                        </router-link>
                    </el-tooltip>
              </div>
          </div>

          
          <el-divider></el-divider>
        </div>

        <div class="live-right-chatinfo-div">
          <div class="live-chatinfo">
            <div v-for="chatinfo, index in chatInfos" :key="index" class="chat-item">
                <el-image
                class="chat-item-img"
                style="width: 50px; height: 50px"
                :src="chatinfo.stuAvatar"
                fit="fill"></el-image>

              <div class="chat-item-info">
                {{chatinfo.stuName}}：{{chatinfo.info}}
              </div>
              
            </div>
          </div>

        </div>


        <div class="live-right-put-chatinfo">
          <!-- <el-divider></el-divider> -->
          <el-input
            class="chatput-input"
            type="textarea"
            :rows="4"
            @keyup.enter.native="putChatInfo"
            placeholder="发条评论吧 :)"
            v-model="chatContent">
          </el-input>
        </div>
    </div>


    <transition name="el-zoom-in-center" v-if="startSign">
    <div class="live-sign" v-loading="signLoading" >
      <div class="live-sign-close" @click="startSign = false">
          <i class="el-icon-circle-close"></i>
      </div>

      <div>
      开始时间：{{signInfo.startTime}} - 结束时间：{{signInfo.endTime}}
      </div>

      <div class="live-sign-div" @click="toSign">
        <div style="position:absolute;">
              签到 <i class="el-icon-s-promotion"></i>
        </div>
        <img :src="img" alt="">
      </div>
    </div>
    </transition>

    <transition name="el-zoom-in-center" v-if="startProblem">
      <div class="live-problem-div">
        <div class="live-sign-close " @click="startProblem = false">
          <i class="el-icon-circle-close"></i>
        </div>

        <div v-html="problemInfo.content">
        </div>
        <div>
          <div v-for="checkInfo,index in problemInfo.checkInfos" 
          class="live-checkInfo-item"
          :key="index">
            <div class="live-checkInfo-item-label">

            {{checkInfo.label}}：{{checkInfo.content}} 
            </div>
            <div>

            <el-radio v-model="problemInfo.check" :label="checkInfo.label" 
            border size="mini">选择</el-radio>
            </div>
          </div>
        </div>
        <div class="submitBtn">
          <el-button type="primary" @click="submitProblem">提交</el-button>
        </div>
      </div>
    </transition>


  </div>
</template>

<script>
import flvjs from 'flv.js/dist/flv.min.js'
import {Storage} from '../storage'

export default {
  data() {
    return {
      chatInfos:[],
      startSign:false,
      signLoading:false,
      startProblem:false,
      img:require('../../public/img/wave.svg'),
      loading:true,
      avater:require('../../public/img/avater.png'),
      chatContent:'',
      liveInfo: {
        pullUrl:'',
        stream:'',
        courseId:'',
        teaId:'',
        teaName:'',
        courseName:'',
        liveName:''
      },
      socket:'',
      stuId:'',
      lockReconnect: false,//是否真正建立连接
      timeout: 3 * 60 * 1000,//3分一次心跳
      timeoutObj: null,//心跳心跳倒计时
      serverTimeoutObj: null,//心跳倒计时
      timeoutnum: null,//断开 重连倒计时
      signInfo:{
        startTime:'',
        endTime:'',
        uuid:'',
        stream:'',
        stuName:''
      },
      stuNumber:'',
      className:"",
      stuName:'',
      stuAvatar:"",
      problemInfo:{
        // type:2,
        content:"",
        checkInfos:[],
        check:'',
        submitContent:""
      }
    }
  },
  methods: {
    putChatInfo() {
      let json = JSON.stringify({
          code:206,
          msg:"chat",
          data: {
            teaId:this.liveInfo.teaId,
            stream:this.liveInfo.stream,
            stuName:this.stuName, 
            stuAvatar:this.stuAvatar, 
            info: this.chatContent
          }
        })
      //发送！
      this.socket.send(json);
      this.chatContent = ""
    },
    addChatItem(json) {
      this.chatInfos.push({
        stuName: json.data.stuName,
        stuAvatar: json.data.stuAvatar,
        info: json.data.info
      })
    },
    startVideo(){
          var videoElement = document.getElementById('videoElement');
          var flvPlayer = flvjs.createPlayer({

              // enableConstVideoViewSize: true,
              // enableDurationMonitor: true,    // true表示监测当前直播流延时，当发现延时过大时，主动追赶
              // enableVideoFrozenMonitor: true, // 监测视频解码是否停滞（画面卡停），当因为某些原因导致无法解码时，将上报VIDEO_FROZEN事件，收到后建议重拉流

              // videoStateMonitorInterval: 5000,
              // maxDurationGap: 2,
              // decreaseDurationStep: 0.4,
              // frozenTimesThreshold: 5,


              type: 'flv',
              enableWorker: true,     //浏览器端开启flv.js的worker,多进程运行flv.js
              isLive: true,           //直播模式
              hasAudio: true,        //开启音频
              hasVideo: true,
              // cors: true,
              stashInitialSize: 60,
              enableStashBuffer: false, //播放flv时，设置是否启用播放缓存，只在直播起作用。
              // url: 'http://127.0.0.1:8080/live/livestream/123.flv'
              url: this.liveInfo.pullUrl

          });
          flvPlayer.attachMediaElement(videoElement);
          flvPlayer.load();
          flvPlayer.play();
    },
    toLinkTheLive(stuId, stream) {
            if(typeof(WebSocket) === "undefined"){
                alert("您的浏览器不支持socket")
            }else{
                // 实例化socket
                this.socket = new WebSocket(`ws://127.0.0.1:8900/live_link/${stuId}/${stream}`)
                // 监听socket连接
                this.socket.onopen = this.onopen
                // 监听socket错误信息
                this.socket.onerror = this.onerror
                // 监听socket消息
                this.socket.onmessage = this.ongetMessage
                this.socket.onclose = this.onclose
            }
    },
    onopen() {
        console.log("ws on open")
        //开启心跳
        this.start();
    },
    onerror() {
        console.log("ws on error")
    },
    ongetMessage(msg) {
        let data = JSON.parse(msg.data);
        // console.log(data)
        //如果是心跳检测的话，那么不予例会
        if(data.code == 202) {
          this.reset();
          return;
        }else if(data.code == 206) {
          this.addChatItem(data)
        }else if(data.code == 204) {
          //204意味着签到
          this.getSignReq(data)
        }else if(data.code == 201) {
          //执行某种操作，接收结果状态回传
          if(data.data.msg != undefined) {
            //这里关掉签到
            this.startSign = false
            //这里关掉问题
            this.startProblem = false
            this.$message({
              message: data.data.msg,
              type: 'success'
            });
          }else {
            this.$message.error(data.data.error);
            this.startSign = false
            this.startProblem = false
          }
        }else if(data.code == 205) {
          //205意味着接收到 要求回复 问题的信息
          this.getProblemReq(data)
        }
        
        //收到服务器信息，心跳重置
        this.reset();
    },
    onclose() {
        // this.socket.close()
        console.log("socket已经关闭")
    },
    reset(){//重置心跳
        //清除时间
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        //重启心跳
        this.start();
    },
    start(){//开启心跳
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(() => {
          // console.log(this.socket)
          //这里发送一个心跳，后端收到后，返回一个心跳消息，
          if (this.socket.readyState == 1) {//如果连接正常
            let r = {code:202, msg:"ping"} 
            
            this.socket.send(JSON.stringify(r));
          }

          // this.serverTimeoutObj = setTimeout(function() {
          //     if(this.socket != '') {
          //       //超时关闭
          //       this.socket.close();
          //     }
          //     //超时后3秒关闭
          // }, 5 * 1000);
 
        }, this.timeout)
    },
    closeLive() {
      API.closeLive(this.live.liveUuid).then(res => {
        if(res.code == 200) {
          
          this.$message({
            message: '关闭成功',
            type: 'success'
          });
          this.liveStart = false
          this.stepIndex = 1
        }else {
          this.$message({
            message: res.data.error,
            type: 'error'
          });
        }
      })
    },
    getSignReq(data) {
      this.startSign = true
      this.signInfo = data.data.signInfo
    },
    toSign() {
      let signInfo = {
        data:{
          stuId: this.stuId,
          stream: this.liveInfo.stream,
          uuid: this.signInfo.uuid,
          stuName:this.stuName
        },
        code: 204
      }

      this.socket.send(JSON.stringify(signInfo));
    },
    getContent(content) {
      this.problemInfo.submitContent = content
    },
    getProblemReq(data) {
      this.startProblem = true
      this.problemInfo = data.data.problemInfo
      console.log(this.problemInfo)
    },
    submitProblem() {
      let problemInfo = {
        data:{
          stuId: this.stuId,
          className:this.className,
          stuNumber:this.stuNumber,
          check: this.problemInfo.check,
          stream: this.liveInfo.stream,
          uuid: this.problemInfo.uuid,
          stuName:this.stuName
        },
        code: 205
      }

      this.socket.send(JSON.stringify(problemInfo));
    }
  },
  mounted(){
    let current_live =  Storage.get("current_live")
    if(current_live != undefined && current_live != '') {
      let stu = Storage.get("stu")
      this.stuId = stu.stuId
      this.stuName = stu.stuName
      this.stuNumber = stu.stuNumber
      this.className = stu.className
      this.stuAvatar = stu.stuAvatar
      console.log(this.stuAvatar)
      
      this.liveInfo = current_live
      this.loading = false
      if (flvjs.isSupported()){
          this.startVideo()
      }

      this.toLinkTheLive(this.stuId, this.liveInfo.stream)
      
    }else {
      this.$router.push( {
            name:"Course",
      })
    }
    
    
  },
  destroyed() {
    this.socket.close()
  }
  
};
</script>

<style>
.live-view {
  margin-top: -2%;
  width: 100%;
  height: calc(100vh);
  
  display: flex;
  position: relative;
}

.live-left {
    width: 85%;
}

.live-video {
    /* object-fit:fill; */
    width: 100%;
    height: 100%;
    background-color: black;
}

.live-right {
    width: 300px;
    display: flex;
    flex-direction: column;
}

.live-right-header {
    font-size: 15px;
    width: 100%;
    /* height: calc(10vh); */

    display: flex;
    flex-direction: column;
    

    overflow: hidden;
}

.live-right-header-info{
  width: 100%;
  display: flex;
  justify-content: space-between;
  /* margin-bottom: -6%; */
}

.live-info {
  width: 200px;
  margin: 4%  4% -3% 4%;
  padding: 1%;
}

.live-info-item {
  text-overflow:ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.close-live {
  min-width: 40px;
  height: 40px;
  margin: 3px 3px;
  text-align: center;
  line-height: 40px;
  border-radius: 50%;

  /* box-shadow: 0 2px 12px 0 rgb(0 0 0 / 20%); */

}

.close-link {
  font-size: 20px;
  color: black;
  text-decoration: none;
  width: 409px;
  height: 40px;
}

.live-right-chatinfo-div {
  width:100%;
  height: 70%;
  overflow:auto;
  /* background-color: black; */
  /* height: calc(75vh);; */
}

.live-chatinfo {
  margin-top: -2%;
  display: flex;
  flex-direction: column;
}

.chat-item {
  /* width: 100%; */
  padding-left: 2%;
  margin: 2%;
  /* min-height: 100px; */
  font-size: 15px;
  display: flex;
  align-items: center;
  margin-bottom: 4%;
  border-radius: 10px;

  /* box-shadow: 0 2px 12px 0 rgb(0 0 0 / 20%); */
}

.chat-item-img {
  min-width: 50px; 
  max-height: 50px;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  align-items: center;
}

.chat-item-info {
  margin-left: 2%;
  display: flex;
  align-items: center;
  
}

.live-right-put-chatinfo {
  width: 96%;
  margin: 2%;
  /* display: flex;
  align-items: center; */
  margin-top: 5%;
  /* height: calc(15vh); */
  /* background-color: cornflowerblue; */
}

.live-right-put-chatinfo > .el-textarea .el-textarea__inner {
  resize:none;
}

.live-sign {
  position: absolute;
  width: 500px;
  height: 200px;
  background-color: white;
  left: 20%;
  top: 20%;
  padding: 2%;
  padding-top: 5%;
  
  display: flex;
  /* justify-content: center; */
  align-items: center;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 15%);
  border-radius: 15px;
}

.live-sign-div {
  margin-top: 20px;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  

  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed rgb(255, 215, 0);
  cursor: pointer;

  overflow: hidden;
}

.live-sign-div > img {
  height: 230px;
  margin-top: -15px;
  transition: all 6s;
  margin-left: 650px;
}

.live-sign-div:hover > img {
  margin-left: -250px;
}

.live-sign-close {
  position: absolute;
  width: 25px;
  height: 25px;
  font-size: 20px;
  right: 2%;
  cursor: pointer;
  top: 18px;
}

.live-problem-div {
  font-size: 15px;
  position: absolute;
  display: flex;
  flex-direction: column;
  width: 340px;
  min-height: 130px;
  left: 20%;
  top: 20%;
  padding: 2%;
  border-radius: 15px;
  background-color: white;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 15%);

}

.live-checkInfo-item {
  margin-top: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.live-checkInfo-item-label {
  /* background-color: tomato; */
  width: 250px;
  word-wrap: break-word;
  
}

.submitBtn {
  margin-top: 10px;
  display: flex;
  
  align-self: center;
}

</style>